#!/bin/sh
#
#-----------------------------------------------------------------------------
# @(#) remoldinstance.sh 
#
# Created by john marsh
#
#
# ------------------------------------------------------------------------------
pname=updateexludelist.sh 
MYNAME="`basename $0`"  ## Name of this Script
MYHOST="`hostname`"     ## Hostname
DATE=`date +%d%b%Y-%T | tr ':' '_'`

PearlBinDir=/opt/hp/nv/bin
computeNodeImage=default-image
edgeNodeImage=edge-image
myworkingDir=`pwd`       # where we are
logdir=${myworkingDir}/removelogs-$USER
LOG=$logdir/removeinstance-${DATE}.log


BOLD=`echo "\033[1m"`
RED=`echo "\033[31m"`
YELLOW=`echo "\033[33m"`
GREEN=`echo "\033[32m"`
CYAN=`echo "\033[36m"`
BLUE=`echo "\033[34m"`
NC=`echo "\033[m"`





function Usage {

   basename=`/bin/basename $0`
   echo " -l Enter the fully qualified path location(s) of the SQL instance to be removed"
   echo " -r Remove instance from headnodes, slave, & edge nodes"
   echo 
   echo
   echo "Example: ./remoldinstance.sh -l /opt/hp/squser1/SQFAAA/ -r  "
   echo "Will run the tool in remove mode on /opt/hp/squser1/SQFAAA/ directory"
   echo
   echo "Example: ./remoldinstance.sh -l /opt/hp/squser1/SQFAAA/,/opt/hp/squser1/SQFBBB/ -r "
   echo "Will remove multiple directories in remove mode for /opt/hp/squser1/SQFAAA/,/opt/hp/squser1/SQFBBB/ "
   echo
   echo " -h Help"
   echo
 }



function GetOpts {

    # Check that arguments exist
    if [ $# -le 2 ]; then

        echo
        echo "ERROR: Wrong number of arguments.  Requires two arguments"
        Usage
        exit 1
    fi


    while getopts "l:rh" arg
      do
      case $arg in

          l)   
             IFS=',' location="${OPTARG}";
             ;;


          r)    
              removeList=1;
              ;;  

          h)
              Usage;
              exit 1;;

          *)
              Usage;
              exit 1;;
      esac

    done

    shift $(($OPTIND - 1))

 }







function ValidateEnv {

  SourceNode=`uname -n`
  echo "Source is: $SourceNode"


  # Next,determine if we are on a Bright Cluster
   if   [ -f "/cm/local/apps/cmd/bin/cmsh"  ] ; then

      printf "${BLUE}This is a Bright Computing Cluster ${NC} \n"
 
      echo "Remove Instance executed by: $USER"  | tee -a $LOG

               
      count=`echo $location | awk -F, {'print NF'}`
      # echo "$count Directories "
      echo | tee -a $LOG
      i=1
      while [ $i -le $count ]
         do
            DIRS[$i]=`echo $location | cut -d, -f${i}`
            echo "${DIRS[$i]} "
 
            # Directory Instance.
            DESTDIR=`echo ${DIRS[$i]}`
            echo "Instance Directory: $DESTDIR"  | tee -a $LOG

            echo "Verifying Source $BACKDIR..."
            echo | tee -a $LOG


            ChkValidDir=`dirname ${DIRS[$i]}`
            if [ "$ChkValidDir" != "/opt/hp/${USER}" ]; then

                echo "*** ERROR: Directory path $ChkValidDir: is an invalid instance path name"
                exit 2

            else
                echo "Directory path ${DIRS[$i]}: is a valid instance path name"
              
            fi



            if [ -d ${DIRS[$i]} ]; then
                 echo "Directory path ${DIRS[$i]} exist on this node" | tee -a $LOG
                   
            else

                echo "*** WARN: Directory path ${DIRS[$i]} either does not exist on this node, or you do not have proper permissions" | tee -a $LOG
                # exit 2             
     
             fi


 
            i=`expr $i + 1`

         done



   # This must not be a Bright Cluster
   else

      printf "${RED}This is NOT a Bright Computing Cluster ${NC} \n"
      exit 1

   fi


  }







# ---------------------------------------------------------
#  Main
# ---------------------------------------------------------


# Parse command line options
  GetOpts $@



# Create log directory 
if [ ! -d $logdir ]; then 
   mkdir $logdir
   chmod +w $logdir
fi  





  unset IFS
  # --------------------------------------------------------
  # change from IFS=',' location=($OPTARG) back to default ' '
  # --------------------------------------------------------





# Welcome Message
echo "======================================================" | tee -a $LOG
date                                                          | tee -a $LOG
echo "$MYNAME : $MYHOST                                     " | tee -a $LOG
echo "======================================================" | tee -a $LOG


  ValidateEnv


  # Get SQimage names
  # SQimages=`ls /cm/images`
  SQimages=`find /cm/images/*/cm/local/apps/cmd/scripts/healthchecks -name cmsh -print 2>/dev/null | cut -d "/" -f 4 |grep -v default-image`

  echo "Images to search:" | tee -a $LOG
  echo "${SQimages[@]} " | tee -a $LOG
   

    if [ "$removeList" = "1" ]; then
	echo "Remove SQ Instance mode is on"
       echo "Remove the SQ instance from the headnode & the headnode images"


       # for DIR in $DIRS
       echo
       echo "Number of Directories to remove:  $count "
       echo "Directories to remove :  ${DIRS[@]} "  
       echo
       for DIR in ${DIRS[@]}

          do

             FinalSlash=`echo -n  "$DIR" | tail -c -1`
             if [ "$FinalSlash" = "/" ] ; then
                  echo "Terminating path slash already present"
                  echo
             else
                  echo "Adding terminating path slash"
                  echo
                  DIR=`echo "$DIR/"`
             fi

             echo "rm -rf ${DIR} "
             rm -rf ${DIR} | tee -a $LOG 
             unset imageName
             for imageName in $SQimages
                do

                   echo "rm -rf /cm/images/${imageName}${DIR} " 
                   rm -rf /cm/images/${imageName}${DIR}  | tee -a $LOG 

                done

             echo "pdsh -a rm -rf ${DIR} "
             pdsh -a rm -rf ${DIR} | tee -a $LOG 

             echo "Sync the backup headnode software image - cmsh -c softwareimage ; updateprovisioners - "
             cmsh -c "softwareimage ; updateprovisioners "

             # Sealog Bad Messages and Overflow files
             echo "Cleanup Sealog Bad Messages and Overflow files"
             # Replace slashes with underscores
             unset temp_dir
             temp_dir=$(echo ${DIR}|sed 's/\//_/g')
             echo "Removing /home/sealog/${USER}/${temp_dir}*"
             rm -rf /home/sealog/${USER}/${temp_dir}* | tee -a $LOG 
             
             echo "Cleanup Problem Management context files"
             echo "Removing /home/pmcontext/${USER}/${temp_dir}*"
             rm -rf /home/pmcontext/${USER}/${temp_dir}* | tee -a $LOG

             echo "Cleanup Vili Harness context files"
             echo "Removing /home/${USER}/context"
             rm -rf /home/${USER}/context | tee -a $LOG

          done



       if [ -e $PearlBinDir/updateexcludelist ]; then

          for DIR in ${DIRS[@]}

              do

                 FinalSlash=`echo -n  "$DIR" | tail -c -1`
                 if [ "$FinalSlash" = "/" ] ; then
                      echo "Terminating path slash already present"
                      echo
                 else
                      echo "Adding terminating path slash"
                      echo
                      DIR=`echo "$DIR/"`
                 fi

                 echo   
                 echo "Modify ${DIR} to the exclude list " 
                 echo "$PearlBinDir/updateexcludelist -l ${DIR} -r " 
                 date
                 $PearlBinDir/updateexcludelist -l ${DIR} -r
                 echo

              done 

       else
           echo
           echo "*** ERROR: Missing $PearlBinDir/updateexcludelist "
           exit 1

       fi
 



    fi


 




